package assignment04;

import gnu.trove.iterator.TIntIterator;

public class IntCounters {
	public static IntCounter normalize(IntCounter counter) {
		IntCounter normalizedCounter = new IntCounter();
		double total = counter.totalCount();
		int key = 0;
		for (TIntIterator it = counter.keySet().iterator(); it.hasNext();) {
			key = it.next();
			normalizedCounter.setCount(key, counter.getCount(key) / total);
		}
		return normalizedCounter;
	}

	public static IntCounterMap conditionalNormalize(IntCounterMap counterMap) {
		IntCounterMap normalizedCounterMap = new IntCounterMap();

		for (TIntIterator outerIt = counterMap.keySet().iterator(); outerIt
				.hasNext();) {
			int key = outerIt.next();
			IntCounter normalizedSubCounter = normalize(counterMap
					.getCounter(key));
			for (TIntIterator innerIt = normalizedSubCounter.keySet()
					.iterator(); innerIt.hasNext();) {
				int value = innerIt.next();
				double count = normalizedSubCounter.getCount(value);
				normalizedCounterMap.setCount(key, value, count);
			}
		}
		return normalizedCounterMap;
	}

	/**
	 * Simple sparse dot product method. Try to put the sparser
	 * <code>Counter</code> as the <code>x</code> parameter since we iterate
	 * over those keys and search for them in the <code>y</code> parameter.
	 * 
	 * @param x
	 * @param y
	 * @return dotProduct
	 */
	public static double dotProduct(IntCounter x, IntCounter y) {
		double total = 0.0;
		for (TIntIterator it = x.keySet().iterator(); it.hasNext();) {
			int keyX = it.next();
			total += x.getCount(keyX) * y.getCount(keyX);
		}
		return total;
	}

}
